# 路由文件夹,用于写路由、数据接口
from datetime import timedelta
from flask import render_template, session, redirect, url_for, request, jsonify, json, current_app
from flask_login import login_required, logout_user, login_user, current_user
from .. import login_manager
from ..sql_operate import *
from . import main


# 页面
# 商品展示页面
# 首页
@main.route('/')
def index():
    if current_user.is_authenticated:
        print("username:%s" % current_user.UserName)
    else:
        print("未登录用户")
    # 找出所有类别和对应的子类，构造json列表
    type_list = get_classes_list()
    return render_template('index.html', type_list=type_list)


# 返回目前分类的json列表
def get_classes_list():
    # 找到所有类别
    types_list = []
    all_goods_types = query_all_goods_types()
    for one_goods_type in all_goods_types:
        all_goods_sub_types = query_all_goods_sub_type_by_goods_types_name(one_goods_type.GoodsTypeName)
        GoodsSubType_list = []
        for one_goods_sub_types in all_goods_sub_types:
            GoodsSubType_list += [{
                "GoodsSubTypeName": one_goods_sub_types.GoodsSubTypeName
            }]
        # 注意看，上面这些{}必须要有[]框起来，否则所有列表会融合在一块，无法达成分块的目的
        print(GoodsSubType_list)
        types_list += [{
            "GoodsType": one_goods_type.GoodsTypeName,
            "GoodsSubType": GoodsSubType_list
        }]
    print(types_list)
    return types_list


# 点击子分类后返回相应分类商品json列表,有多个商品可选
@main.route('/all_goods_in_one_goods_sub_type_name/<goods_sub_type_name>', methods=['POST', 'GET'])
def all_goods_in_one_goods_sub_type(goods_sub_type_name):
    print(goods_sub_type_name)
    # 得到子类下相应的所有商品的信息
    if query_goods_sub_type_by_goods_sub_type_name(goods_sub_type_name) is None:
        return jsonify({'code': 400, 'data': None})
    # (返回json信息，让前端构建页面）
    all_goods = query_all_goods_by_goods_sub_type_name(goods_sub_type_name)
    goods_list = []
    for one_goods in all_goods:
        goods_list += [{
            "GoodsID": one_goods.GoodsID,
            "GoodsName": one_goods.GoodsName,
            "GoodsPrice": one_goods.GoodsPrice,
            "GoodsCount": one_goods.GoodsCount,
            "GoodsSell": one_goods.GoodsSell
        }]
    json_list = {
        'code': 200,
        'data': {
            "GoodsSubType": goods_sub_type_name,
            "Goods": goods_list
        }
    }
    print(json_list)
    return jsonify(json_list)


# 认证页面
# 登录
@main.route('/login/', methods=['POST', 'GET'])
def login():
    if request.method == "GET":  # 导航到登录页
        print("登录页")
        # 这里应该传入用户信息以判断用户是否登录
        return render_template('auth/login.html')
    else:  # ajax信息接收
        # 这里应该增加判断是否有东西
        data = json.loads(request.form.get('data'))
        username = data['username']  # 标志用户名:判断插入数据库的位置
        password = data['password']
        print(username)
        print(password)
        # 根据用户名查找用户
        user_query_result = User.query.filter_by(UserName=username).first()
        if user_query_result is None:
            print('找不到此用户！')
            return jsonify({
                'message': u'无效的用户名',
                'code': 400
            })
        elif user_query_result.validate_password(password):
            # 用户登录,顺便可以完成'记住我'的功能
            # login_user(user, remember=form.remember.data)
            # 记录用户的登录状态
            login_user(user_query_result, True)
            # 设置session过期时间 过期时间一天
            session.permanent = True
            app = current_app._get_current_object()
            app.permanent_session_lifetime = timedelta(days=1)
            print('登录成功')
            return jsonify({
                'message': u'登录成功！',
                'code': 200
            })
        else:
            print('密码错误！')
            return jsonify({
                'message': u'无效的密码',
                'code': 401
            })


# 注销
@main.route('/logout/', methods=['POST', 'GET'])
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.index'))


# 注册
@main.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('auth/register.html')
    else:
        data = json.loads(request.form.get('data'))
        username = data['username']  # 标志用户名:判断插入数据库的位置
        password = data['password']
        print(username)
        print(password)
        # 根据用户名查找用户
        if query_user_by_UserName(username) is None:
            # 根据表单数据创建用户对象
            create_user(UserName=username, UserPassword=password)
            print('注册成功')
            user_query_result = query_user_by_UserName(username)
            login_user(user_query_result, True)
            # 设置session过期时间 过期时间一天
            session.permanent = True
            app = current_app._get_current_object()
            app.permanent_session_lifetime = timedelta(days=1)
            # 跳转到指定位置
            return jsonify({
                'message': u'注册成功！',
                'code': 200
            })
        else:
            print('用户名已被注册')
            return jsonify({
                'message': u'用户名已被注册！',
                'code': 402
            })


# 用户登录状态管理用
@login_manager.user_loader
def load_user(user_id):
    user = User.query.get(int(user_id))
    return user


# 交易页面
# 购物车页
@main.route('/shopping_car/', methods=['GET'])
@login_required
def shopping_car():
    if request.method == 'GET':
        buycar_list = get_buycar_list()
        return render_template('transaction/shopping_cart.html', buycar_list=buycar_list)


# 返回目前分类的json列表
def get_buycar_list():
    # 找到所有购物车
    buycar_list = []
    userid = current_user._get_current_object().UserID
    all_buycar = query_all_BuyCar_by_UserID(userid)
    for one_buycar in all_buycar:
        buycar_list += [{
            "BuyCarID": one_buycar.BuyCarID,
            "GoodsName": one_buycar.GoodsName,
            "GoodsPrice": one_buycar.GoodsPrice,
            "BuyCarNumber": one_buycar.BuyCarNumber,
            "TotalPrice": one_buycar.TotalPrice,
        }]
    return buycar_list


# 因为shopping_car有@login_required阻挡，有点问题，所以我把get和post逻辑拆开了
@main.route('/add_shopping_car/', methods=['POST'])
def add_shopping_car():
    if not current_user.is_authenticated:
        print("添加购物车前先登录用户啊！")
        return jsonify({"code": 405})
    else:
        # 接收"首页添加购物车"传来的信息
        data = json.loads(request.form.get('data'))
        goodsid = data['GoodsID']
        buycarnumber = int(data['BuyCarNumber'])
        # 通过goodsid查goods，检验是否存在此商品（其实还可以检验商品存货数量）
        goods = query_goods_by_GoodsID(goodsid)
        if goods is None:
            print("找不到此商品号")
            return jsonify({"code": 406})
        elif goods.GoodsCount < buycarnumber:
            return jsonify({"code": 409})
        # 通过userid和goodsid查buycarid，如果有该种类的buycarid则只是增加数量，否则需要新建buycar
        userid = current_user._get_current_object().UserID
        buycar = query_BuyCar_by_UserID_And_GoodsID(userid, goodsid)
        if buycar is None:
            print("该商品未添加到购物车上，正在创建购物车并添加……")
            goodsname = goods.GoodsName
            goodsprice = goods.GoodsPrice
            totalprice = int(buycarnumber) * float(goodsprice)
            # 将商品ID、数量等信息添加进购物车
            create_BuyCar(userid, goodsid, goodsname, buycarnumber, goodsprice, totalprice)
            print("添加购物车成功")
            return jsonify({"code": 200})
        else:
            print("该商品已添加到购物车上，正在增加购物车上该商品的数量……")
            add_BuyCarNumber_By_BuyCarID_And_BuyCarNumber(buycar.BuyCarID, buycarnumber)
            return jsonify({"code": 201})


@main.route('/delete_shopping_car/', methods=['POST'])
def delete_shopping_car():
    data = json.loads(request.form.get('data'))
    BuyCarID = data['BuyCarID']
    print(BuyCarID)
    delete_BuyCar_by_BuyCarID(BuyCarID)
    return jsonify({"code": 200})


# 订单页
@main.route('/order/', methods=['GET', 'POST'])
@login_required
def order():
    if request.method == 'GET':
        order_list = get_order_list()
        return render_template('transaction/order.html', order_list=order_list)
    else:
        # 接收"购物车页提交订单"传来的信息
        data = json.loads(request.form.get('data'))
        print(data['code'])
        userid = current_user._get_current_object().UserID
        # 判断data的购物车项是否大于0
        all_buycar = query_all_BuyCar_by_UserID(userid)
        if not all_buycar:
            print("all_buycar is None")
            return jsonify({"code": 407})
        print("all_buycar is not None")
        goods_count_is_full = True
        count_not_full_GoodsName_list = []
        totalPay = 0.0
        for item in all_buycar:
            goodsid = item.GoodsID
            print()
            buycarnumber = item.BuyCarNumber
            goods = query_goods_by_GoodsID(goodsid)
            if goods.GoodsCount < buycarnumber:
                goods_count_is_full = False
                count_not_full_GoodsName_list += [{
                    "count_not_full_GoodsName": goods.GoodsName
                }]
            totalPay += buycarnumber*goods.GoodsPrice
        # 返回成功或失败（比如钱不够、商品库存不够）
        if not goods_count_is_full:
            return jsonify({"code": 409, "count_not_full_GoodsName_list": count_not_full_GoodsName_list})
        if totalPay > current_user._get_current_object().UserMoney:
            return jsonify({"code": 411})
        # 先创建Order
        orderid = create_order_return_OrderID(userid)
        print("orderid为")
        print(orderid)
        for item in all_buycar:
            # 取出每一条购物车项
            buycarid = item.BuyCarID
            goodsid = item.GoodsID
            buycarnumber = item.BuyCarNumber
            # 通过BuyCarID将所有信息装入OrderItem里
            # 其实这里需要着重判断Goods的各种情况，但我没有时间开发
            create_order_item(orderid, goodsid, buycarnumber)
            decrease_GoodsCount_And_increase_GoodsSell_by_GoodsID_And_BuyNumber(goodsid, buycarnumber)
            # 删除相应的购物车项
            delete_BuyCar_by_BuyCarID(buycarid)
        this_order = query_order_by_OrderID(orderid)
        print("this_order.TotalPayment")
        print(this_order.TotalPayment)
        decrease_UserMoney_by_UserID_And_Money_Decrement(userid, this_order.TotalPayment)
        print("添加订单成功")
        return jsonify({"code": 200})


# 获取该用户所有的订单
def get_order_list():
    order_list = []
    userid = current_user._get_current_object().UserID
    # 找到该用户下的所有订单
    all_order = query_all_order_by_UserID(userid)
    for one_order in all_order:
        # 找到该订单下所有订单项
        order_item_list = []
        all_order_item = query_all_order_item_by_OrderID(one_order.OrderID)
        for one_order_item in all_order_item:
            order_item_list += [{
                "GoodsName": one_order_item.GoodsName,
                "GoodsPrice": one_order_item.GoodsPrice,
                "BuyNumber": one_order_item.BuyNumber,
                "ItemPayment": one_order_item.ItemPayment,
            }]
        order_list += [{
            "OrderID": one_order.OrderID,
            "CreateTime": one_order.CreateTime,
            "TotalPayment": one_order.TotalPayment,
            "orderItems": order_item_list,
        }]
    return order_list


# 个人信息页面
# 个人中心
@main.route('/personals/', methods=['GET', 'POST'])
@login_required
def personals():
    if request.method == 'GET':
        personals_info_list = get_personals_info_list()
        return render_template('personal/personal.html', personals_info_list=personals_info_list)
    else:
        # 接收"保存修改的信息"传来的信息，应该有UserID、用户名、密码、地址等。
        data = json.loads(request.form.get('data'))
        userid = current_user._get_current_object().UserID
        username = data["username"]
        if username == "":                               # 如果修改用户名为空，则不修改用户名
            username = None
        else:
            userA = query_user_by_UserID(userid)
            userB = query_user_by_UserName(username)
            # 如果并没有修改用户名则不修改
            if userB is not None:
                if userA.UserID != userB.UserID:
                    return jsonify({"code": 402})    # 如果这个用户名有人在用并且这个人不是他自己
        # 如果这个用户名有人并且这个人是他自己 或者说 这个用户名还没被人用过

        password = data["password"]
        if password == "":
            password = None

        address = data["address"]
        if address == "":
            address = None
        update_user(userid, username, password, address, None)
        return jsonify({"code": 200})


# 获得个人信息列表
def get_personals_info_list():
    userid = current_user._get_current_object().UserID
    user = query_user_by_UserID(userid)
    if user is None:
        print("找不到该用户！")
        return {}
    else:
        if user.UserAddress is None:
            print("user.UserAddress is None")
            Temp_UserAddress = ""
        else:
            Temp_UserAddress = user.UserAddress
        personals_info_list = {
            "UserID": user.UserID,
            "UserName": user.UserName,
            "UserAddress": Temp_UserAddress,
            "UserMoney": user.UserMoney,
        }
        return personals_info_list


# 用户头像收发
# @main.route('/avatar/<string:UserID>', methods=['get', 'post'])
# def avatar(UserID):
#     # if request.method == "GET":  # 返回图片URL给前端
#     #     userAvatarPath = query_UserAvatarPath_by_UserID(UserID)
#     #     if os.path.isfile(os.path.join(current_app.config['User_Avatar_Dir'], userAvatarPath)):
#     #         return userAvatarPath
#     # el
#     if request.method == 'POST' and 'avatar' in request.files:
#         avatar_data = request.files.get('avatar')
#         avatar_file_avatar = rename_avatar(UserID)
#         avatar_data.save(os.path.join(current_app.config['User_Avatar_Dir'], avatar_file_avatar))
#         # 调用
#         print('上传头像成功,上传的用户ID是:' + str(UserID))
# #         返回json成功code

